import cTitle from "components/title";
import cMyswipe from "components/myswipe";
import purchaseNotes from "../consumptionComm/purchaseNotes/purchaseNotes";
import addressUs from "../consumptionComm/addressUs/addressUs";
import yzService from "components/ui_components/yz_service.vue";
import { Toast } from "vant";
export default {
  data() {
    return {
      locationStatus: false, //定位开关
      couponName: "",
      beginStatus: 0,
      storeName: "",
      storeDetail: {},
      goodsId: 0,
      addressDetail: "", //地址信息
      imageRight: false,
      favorite: false, //收藏开关
      shareShow: false, //打开分享弹窗
      posterImg: "", //海报信息
      posterShow: false,
      goodsDetails: {},
      goodsPlugin: {}, //原有的详情数据
      goodsBanner: "",
      couponStoreGoods: {},
      getGoods: {},
      fightGroupsId: 0, //是否开团，0未开团
      pluginSetting: {},

      //客服插件
      customerOpen: false, //客服弹窗开关
      serviceShow: false,
      serviceQRcode: "",
      serviceMobile: "",
      cservice: "",
      storeListByGoods: [],
      longitude: "",
      latitude: "",
      activity_id: "",
      discountLeftWidth: 0,
      discountRightWidth: 0,
      advertising:{}, //广告宣传语
      taglineText:'',
      showBigImg: false,
      isMiniApp: window.isMiniprogram ? true : false,
      total: 0,
      bigImages: [], //商品详情富文本图片预览
      imgStart: 0
    };
  },
  activated() {
    this.goodsId = Number(this.$route.query.goodsId);
    this.serviceDetail();
    this.fun
      .getLocation()
      .then(res => {
        let p = this.fun.bd_encrypt(res.point.lng, res.point.lat);
        this.latitude = p.lat;
        this.longitude = p.lng;
        this.getGoodsDetails(this.goodsId);
        this.getStoreListByGoods();
        this.locationStatus = true;
      })
      .catch(err => {
        console.log(err);
        this.locationStatus = false;
      });
    this.initData();
  },
  computed: {
    setTimeStart() {
      let time = new Date(this.couponStoreGoods.start_time * 1000);
      return time.getTime() - new Date().getTime();
    },
    setTimeEnd() {
      let time = new Date(this.couponStoreGoods.end_time * 1000);
      return time.getTime() - new Date().getTime();
    },
    toFixInt() {
      return function(value) {
        return parseFloat(value) || '0';
      }
    }
  },
  methods: {
    initData() {
      this.showBigImg = false;
      this.$emit("setShowBigImg", this.showBigImg);
    },
    toGroupCode() {
      //群活码跳转功能
      if (this.goodsPlugin.group_code.jump_mode === "home") {
        this.$router.push(this.fun.getUrl("groupCode"));
      } else if (this.goodsPlugin.group_code.code_url) {
        window.location.href = this.goodsPlugin.group_code.code_url;
      }
    },
     // 广告语跳转
     goAdvertisingLink(link) {
      if(link) {
        window.location.href = link;
      }
      
    },
    onPreorder() {
      //跳转预下单
      if (this.getGoods.show_stock === 0) {
        Toast('"商品没有库存了');
        return;
      }
      this.$router.push(this.fun.getUrl("orderAffirm", {}, { goodsId: this.goodsId, optionsId: "", total: 1 }));
    },
    locationOn() {
      //定位功能
      this.fun
        .getLocation()
        .then(res => {
          let p = this.fun.bd_encrypt(res.point.lng, res.point.lat);
          this.latitude = p.lng;
          this.longitude = p.lat;
          this.getGoodsDetails(this.goodsId);
          this.getStoreListByGoods();
          this.locationStatus = true;
        })
        .catch(err => {
          console.log(err);
          this.locationStatus = false;
        });
    },
    shopNavTo() {
      let jsonObj = {
        goodsId: this.goodsId,
        storeName: this.storeDetail.store_name,
        longitude: this.longitude,
        latitude: this.latitude
      };
      this.$router.push(this.fun.getUrl("shopList", {}, jsonObj));
    },
    goodsGroup() {
      if (this.getGoods.show_stock === 0) {
        Toast("商品没有库存了");
        return;
      }
      this.$router.push(this.fun.getUrl("GroupGoods", { id: this.couponStoreGoods.fight_groups_id, name: "group" }));
    },
    onFavorite() {
      let favorite = !this.favorite;
      let api = "";
      if (favorite) {
        api = "member.member-favorite.store";
      } else {
        api = "member.member-favorite.destroy";
      }
      $http.get(api, { goods_id: this.goodsId }, "正在获取").then(
        response => {
          if (response.result == 1) {
            this.favorite = favorite;
            Toast(response.msg);
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          // console.log(response);
          // error callback
        }
      );
    },
    onMenuShare() {
      this.$dialog.alert({ message: "请点击右上角微信分享" });
      // wx.config({
      //   // 配置信息, 即使不正确也能使用 wx.ready
      //   debug: false,
      //   appId: "",
      //   timestamp: 1,
      //   nonceStr: "",
      //   signature: "",
      //   jsApiList: []
      // });
      // wx.ready(function() {
      //   let that = this;
      //   wx.onMenuShareAppMessage({
      //     title: that.getGoods.title, // 分享标题
      //     desc: "", // 分享描述
      //     link: window.location.href, // 分享链接
      //     imgUrl: that.goodsBanner, // 分享图标,填写绝对路径
      //     type: "link", // 分享类型,music、video或link，不填默认为link
      //     success: function() {
      //       // 用户确认分享后执行的回调函数
      //     },
      //     cancel: function() {
      //       // 用户取消分享后执行的回调函数
      //     }
      //   });
      // });
    },
    goodsPoster() {
      //海报信息设置
      let json = {
        goods_id: this.goodsId
      };
      $http.post("plugin.coupon-store.frontend.poster.goodsPoster", json, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.posterImg = res.url;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    tapIndex() {
      //首页跳转
      this.$router.replace(this.fun.getUrl("home", {}, {}));
    },
    clickChat() {
      let setServicePlugin = this.fun.isTextEmpty(this.serviceMobile) && this.fun.isTextEmpty(this.serviceQRcode);
      if (this.fun.isTextEmpty(this.cservice) && setServicePlugin) {
        return this.$toast("抱歉，暂未设置客服信息");
      }
      if (!this.fun.isTextEmpty(this.cservice) && setServicePlugin) {
        //只设置了客服链接，直接跳转
        if (this.cservice && this.cservice.indexOf("chatWindow") >= 0) {
          window.location.href = this.cservice + "&goods_id=" + this.$route.params.id;
        } else {
          window.location.href = this.cservice;
        }
        return;
      }
      this.serviceShow = true;
    },
    serviceDetail() {
      $http.post("goods.customer-service.index", { goods_id: this.goodsId }, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            this.cservice = res.cservice;
            this.serviceQRcode = res.service_QRcode;
            this.serviceMobile = res.service_mobile;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    getGoodsDetails(id) {
      let json = {
        id: Number(id),
        basic_info: 1
      };
      $http.post("goods.goods.get-goods-page", json, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            let couponStoreGoods = res.plugin?.coupon_store_goods;
            let startTime = couponStoreGoods.start_time * 1000;
            let endTime = couponStoreGoods.end_time * 1000;
            let nowtime = new Date().getTime();
            let beginStatus = 0;
            if (startTime > nowtime) {
              beginStatus = 0;
            } else if (nowtime >= startTime && nowtime < endTime) {
              beginStatus = 1;
            } else {
              beginStatus = 2;
            }
            this.goodsBanner = res.get_goods.thumb;
            this.fightGroupsId = res.plugin.coupon_store_goods?.fight_groups_id;
            this.couponStoreGoods = res.plugin?.coupon_store_goods;
            this.getGoods = res.get_goods;
            this.goodsPlugin = res.plugin;
            this.beginStatus = beginStatus;
            this.pluginSetting = response.basic_info?.plugin_setting?.coupon_store;
            this.favorite = res.is_favorite?.status ? true : false;
            this.bigImages = this.getImgSrc(this.getGoods.content);
            this.advertising = res?.get_goods?.has_one_goods_advertising ?? {};
            this.taglineText = this.textareaTo(this.advertising?.copywriting)
            this.$nextTick(() => {
              this.discountLeftWidth = this.$refs?.discountLeft?.clientWidth;
              this.discountRightWidth = this.$refs?.discountRight?.clientWidth;
            });

            // console.log(this.$refs.discountRight.$el.offsetHeight);
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    textareaTo(str) {
        let regs = new RegExp("\r", "g");
        let reg = new RegExp("\n", "g");
        let regSpace = new RegExp(" ", "g");
        str = str?.replace(reg, "<br/>");
        str = str?.replace(regs, "<br/>");
        str = str?.replace(regSpace, "&nbsp;");
        return str;
    },
    getStoreListByGoods() {
      let json = {
        goods_id: this.goodsId,
        store_name: "",
        longitude: this.longitude,
        latitude: this.latitude
      };
      $http.post("plugin.coupon-store.frontend.store.getStoreListByGoods", json, "正在获取").then(
        response => {
          if (response.result == 1) {
            let res = response.data;
            let storeaddress = res.data;
            let addressDetail = `${storeaddress[0].city}${storeaddress[0].district}${storeaddress[0].street}${storeaddress[0].address}`;
            this.addressDetail = addressDetail;
            this.storeListByGoods = res.data;
            this.total = res.total;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    showPop() {
      //打开客服弹窗
      let setServicePlugin = app._isTextEmpty(this.data.serviceQRcode) && app._isTextEmpty(this.data.serviceMobile);
      if (app._isTextEmpty(this.data.cservice) && setServicePlugin) {
        return app.tips("抱歉，暂未设置客服信息");
      }
      if (!app._isTextEmpty(this.data.cservice) && setServicePlugin) {
        this.gotoChat({
          currentTarget: {
            dataset: {
              cservice: this.data.cservice
            }
          }
        }); //只设置了客服链接，直接跳转
        return;
      }
      this.setData({
        serviceShow: true
      });
    },
    sharePopup() {
      this.shareShow = true;
    },
    closePop() {
      this.serviceShow = false;
    },
    PosterClose() {
      this.posterShow = false;
    },
    shareClose() {
      this.shareShow = false;
    },
    PosterPopup() {
      this.posterShow = true;
      this.goodsPoster();
    },
    callPhone() {
      window.location.href = "tel://" + this.serviceMobile;
    },
    callStore() {
      window.location.href = "tel://" + this.storeListByGoods[0].store_mobile;
    },
    saveImg() {},
    copyWriting() {
      this.$router.push(this.fun.getUrl("copyWriting", {}, { goodsId: this.goodsId }));
    },
    setShowBigImg(data) {
      this.child_showBigImg = data;
      this.$emit("setShowBigImg", data);
    },
    handleHtml() {
      if ($event.target) {
        if ($event.target.nodeName == "IMG" && $event.target.parentElement.nodeName !== "A") {
          for (let i = 0; i < this.bigImages.length; i++) {
            // 编程式
            if ($event.target.currentSrc.indexOf(this.bigImages[i]) > -1) {
              this.imgStart = i;
              this.showBigImg = true;
              this.$emit("setShowBigImg", this.showBigImg);
              return;
            }
          }
        }
      }
    },
    getImgSrc(richtext) {
      let imgList = [];
      richtext.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
        imgList.push(capture);
      });
      return imgList;
    }
  },
  components: {
    purchaseNotes,
    addressUs,
    cTitle,
    yzService,
    cMyswipe
  }
};
